/*
 * sync.c
 *
 *  Created on: Dec 23, 2010
 *      Author: cesar
 */

#include "sync.h"

int syncFolders(p_st_folder f1, p_st_folder f2, char *uriF1, char *uriF2, int mode){

	//DebugPrint("Sincronizando pasta %s com %s", f1->ent->d_name, f2->ent->d_name);

	if(mode & SYNC_TO_1){
		copyFiles(f2, uriF2, uriF1);
	}
	if(mode & SYNC_TO_2){
		copyFiles(f1, uriF1, uriF2);
	}
}

int copyFiles(p_st_folder folderSt, char *uriBase, char *uriCopy){
	//Variaveis Locais
	int i;
	FILE *inF, *ouF;
	char *newUriBase = NULL;
	char *newUriCopy = NULL;
	int maxLenUriBase = 256;
	int maxLenUriCopy = 256;
	int lenUriBase, lenUriCopy;
	char buffer[BUFFER_SIZE];
	int bytes;
	DIR *dir;

	if(folderSt != NULL){

		lenUriBase = strlen(uriBase);
		lenUriCopy = strlen(uriCopy);
		newUriBase = malloc(maxLenUriBase);
		newUriCopy = malloc(maxLenUriCopy);

		for(i=0; i<folderSt->num_files; i++){
			if(folderSt->diff_files[i] == 1){
				if(maxLenUriBase < lenUriBase + strlen(folderSt->files[i]->d_name)){
					maxLenUriBase *= 2;
					newUriBase = realloc(newUriBase, maxLenUriBase);
				}
				sprintf(newUriBase, "%s/%s", uriBase, folderSt->files[i]->d_name);

				if(maxLenUriCopy < lenUriCopy + strlen(folderSt->files[i]->d_name)){
					maxLenUriCopy *= 2;
					newUriCopy = realloc(newUriCopy, maxLenUriCopy);
				}
				sprintf(newUriCopy, "%s/%s", uriCopy, folderSt->files[i]->d_name);

				printf("%s to %s\n", newUriBase, newUriCopy);

				if((ouF = fopen(newUriCopy, "r")) == NULL){
					if((ouF = fopen(newUriCopy, "wb+")) == NULL) {
						perror("open uriCopy");
						exit(-1);
					}

					if(((inF = fopen(newUriBase, "rb"))) == NULL) {
						perror("open uriBase");
						exit(-1);
					}

					while((bytes = fread(buffer, 1, BUFFER_SIZE, inF)) > 0){
						fwrite(buffer, 1, bytes, ouF);
					}

					fclose(inF);
					fclose(ouF);
				}
				else{
					fclose(ouF);
				}
			}
		}

		for(i=0; i<folderSt->num_folders; i++){

			if(folderSt->diff_folders[i] == 1){
				if(maxLenUriBase < lenUriBase + strlen(folderSt->folders[i]->ent->d_name)){
					maxLenUriBase *= 2;
					newUriBase = realloc(newUriBase, maxLenUriBase);
				}
				sprintf(newUriBase, "%s/%s", uriBase, folderSt->folders[i]->ent->d_name);

				if(maxLenUriCopy < lenUriCopy + strlen(folderSt->folders[i]->ent->d_name)){
					maxLenUriCopy *= 2;
					newUriCopy = realloc(newUriCopy, maxLenUriCopy);
				}
				sprintf(newUriCopy, "%s/%s", uriCopy, folderSt->folders[i]->ent->d_name);

				printf("%s to %s\n", newUriBase, newUriCopy);

				if((dir = opendir (newUriCopy)) != NULL){
					closedir(dir);
				}
#ifdef _WIN32
				else if(-1 == mkdir(newUriCopy)){
					perror("mkdir Error");
				}
#else
				else if(-1 == mkdir(newUriCopy, S_IRWXU)){
					perror("mkdir Error");
				}
#endif

				copyFiles(folderSt->folders[i], newUriBase, newUriCopy);
			}
		}

		free(newUriBase);
		free(newUriCopy);
	}

	return 0;
}
